﻿using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using Model;
using System.Drawing;

namespace TaxiDispatchClient
{
    public partial class TaxiSetRectForm : DevExpress.XtraEditors.XtraForm
    {
        public TaxiSetRectForm()
        {
            InitializeComponent();
            string strWhere = "";
            if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
            {
                strWhere = "CompanyName='" + MainForm.MyUserInfo.CompanyName + "'";
                radioGroup_SelectType.Properties.Items.RemoveAt(3);
            }
            //Gridcontrol1
            DataSet ds = MainForm.PositionService.TaxiInfoGetList(strWhere);
            gridControl1.DataSource = ds.Tables[0];
            //gridView1.Columns["id"].Caption = "流水号";
            //gridView1.Columns["id"].Width = 56;
            //gridView1.Columns["id"].AppearanceHeader.TextOptions.HAlignment =
            //    DevExpress.Utils.HorzAlignment.Center;
            //gridView1.Columns["id"].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            //gridView1.Columns["TaxiNo"].Caption = "牌照";
            //gridView1.Columns["TaxiNo"].Width = 86;
            //gridView1.Columns["TaxiGroupid"].Visible = false;
            //gridView1.Columns["TaxiType"].Caption = "型号";
            //gridView1.Columns["TaxiType"].Width = 86;
            //gridView1.Columns["Taxigroup"].Caption = "分组";
            //gridView1.Columns["CompanyName"].Caption = "所属公司";
            //gridView1.Columns["CompanyName"].Width = 86;
            //mainMap
            mainMap.Manager.Mode = AccessMode.ServerAndCache;
            mainMap.MapProvider = GMapProviders.GoogleChinaMap;
            double theCenterLat = Properties.Settings.Default.MainMapLat;
            double theCenterLng = Properties.Settings.Default.MainMapLng;
            mainMap.MaxZoom = 18;
            mainMap.MinZoom = 8;
            mainMap.Zoom = 12;
            mainMap.Position = new PointLatLng(theCenterLat, theCenterLng);
            mainMap.DragButton = MouseButtons.Left;
            _rectange = new GMapOverlay("rectange");
            mainMap.Overlays.Add(_rectange);

            // trackBarControl_MapZoom
            trackBarControl1.Properties.Minimum = mainMap.MinZoom;
            trackBarControl1.Properties.Maximum = mainMap.MaxZoom;
            trackBarControl1.Value = int.Parse(mainMap.Zoom.ToString());

            timeEdit_start.Time = DateTime.Parse("00:00");
            timeEdit_end.Time = DateTime.Parse("23:59");
        }

        private readonly GMapOverlay _rectange;
        private void simpleButton_Select_Click(object sender, EventArgs e)
        {
           // string parameter;
           // string parameterVaule = textEdit_condition.Text;
           // if (radioGroup_SelectType.SelectedIndex == 0)
           // {
           //     parameter = "TaxiNo";
           // }
           // else if (radioGroup_SelectType.SelectedIndex == 1)
           // {
           //     parameter = "TaxiType";
           // }
           // else if (radioGroup_SelectType.SelectedIndex == 2)
           // {
           //     parameter = "Remark";
           // }
           // else
           // {
           //     if(textEdit_condition.Text.Trim() =="")
           //     {
           //         DataSet ds1 = MainForm.PositionService.TaxiInfoGetList("");
           //         gridControl1.DataSource = ds1.Tables[0];
           //         gridView1.GroupPanelText = "当前一共" +
           //             ds1.Tables[0].Rows.Count + "辆出租车";
           //         return;
           //     }
             
           //         parameter = "Taxigroup";
              
           // }
           //DataSet ds = MainForm.PositionService.TaxiInfoGetListWithPar(parameter, parameterVaule);
            StringBuilder strWhere = new StringBuilder();
            string para=radioGroup_SelectType.Properties.Items[
               radioGroup_SelectType.SelectedIndex].Value.ToString();
            string paraVaule = textEdit_condition.Text;
            if (paraVaule.Trim()=="")
            {
                if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
                {
                    strWhere.Append("CompanyName='");
                    strWhere.Append(MainForm.MyUserInfo.CompanyName);
                    strWhere.Append("'");
                }
            }
            else
            {
                strWhere.Append(para);
                strWhere.Append(" like '%");
                strWhere.Append(paraVaule);
                strWhere.Append("%' ");
                if (MainForm.MyUserInfo.CompanyName != Service.PowerConfig.MainCompanyName)
                {
                    strWhere.Append(" and CompanyName='");
                    strWhere.Append(MainForm.MyUserInfo.CompanyName);
                    strWhere.Append("'");
                }  
            }
            try
            {
                DataSet ds = MainForm.PositionService.TaxiInfoGetList(strWhere.ToString());
                gridControl1.DataSource = ds.Tables[0];
                gridView1.GroupPanelText = "当前一共" + ds.Tables[0].Rows.Count + "辆出租车";
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex,true);
            }
            
        }

        private void trackBarControl1_Properties_ValueChanged(object sender, EventArgs e)
        {
            mainMap.Zoom = trackBarControl1.Value;
        }

        private void mainMap_OnMapZoomChanged()
        {
            trackBarControl1.Value = (int)mainMap.Zoom;
        }

        private void simpleButton_set_Click(object sender, EventArgs e)
        {
            if(gridView1.RowCount<1)
            {
                XtraMessageBox.Show("请选择至少一辆出租车");
                radioGroup_SelectType.Focus();
                return;
            }
            if (!CheckedPass())
                return;
            double  leftLat ;
            double leftLng ;
            double rightLat ;
            double  rightLng ;

            leftLat = Convert.ToDouble(textEdit_leftlat.Text.Trim());
            leftLng = Convert.ToDouble(textEdit_leftlon.Text.Trim());
            rightLat = Convert.ToDouble(textEdit_rightlat.Text.Trim());
            rightLng = Convert.ToDouble(textEdit_rightlon.Text.Trim());
            string strStarttime = timeEdit_start.Text.ToString();
            string strEndtime = timeEdit_end.Text.ToString();
            int count = 0;
            try
            {
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    int intId = int.Parse(gridView1.GetDataRow(i)["id"].ToString());
                    TaxiAreaInfo taxiArea = new TaxiAreaInfo
                    {
                        Taxiid = intId,
                        LeftLat = leftLat,
                        LeftLon = leftLng,
                        RightLat = rightLat,
                        RightLon = rightLng,
                        STime = strStarttime,
                        ETime = strEndtime
                    };
                    if (MainForm.PositionService.TaxiAreaExit(intId))
                    {
                        if (MainForm.PositionService.TaxiAreaUpdate(taxiArea))
                        {
                            count++;
                        }
                    }
                    else
                    {  
                       if( MainForm.PositionService.TaxiAreaAdd(taxiArea) )
                       {
                           count++;   
                       }
                    }
                        
                }
                XtraMessageBox.Show("成功设置【"+count.ToString()+"辆】出租车矩形区域");
                
            }
           catch(Exception ex)
           {
               Common.CommonRoutine.HandlingExceptions(ex,true);
               return;
           }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            RectLatLng area = mainMap.SelectedArea;
            if (!area.IsEmpty)
            {
                //textEdit_leftlat.Text = area.Lat.ToString();
                //textEdit_leftlon.Text = area.Lng.ToString();
                //textEdit_rightlat.Text = (area.Lat - area.HeightLat).ToString();
                //textEdit_rightlon.Text = (area.Lng + area.WidthLng).ToString();
                textEdit_leftlat.Text = area.LocationTopLeft.Lat.ToString();
                textEdit_leftlon.Text = area.LocationTopLeft.Lng.ToString();
                textEdit_rightlat.Text = area.LocationRightBottom.Lat.ToString();
                textEdit_rightlon.Text = area.LocationRightBottom.Lng.ToString();
               
            }
            else
            {
                textEdit_leftlat.Text = "未设置";
                textEdit_leftlon.Text = "未设置";
                textEdit_rightlat.Text = "未设置";
                textEdit_rightlon.Text = "未设置";
            }
             
        } 
        private bool CheckedPass()
        {
            string leftLat = textEdit_leftlat.Text.Trim();
            string leftLng = textEdit_leftlon.Text.Trim();
            string rightLat = textEdit_rightlat.Text.Trim();
            string rightLng = textEdit_rightlon.Text.Trim();
            if(leftLat=="未设置")
            {
                XtraMessageBox.Show("请在地图中按Shift键，拖动反键选取区域");
                textEdit_leftlat.Focus();
                return false;
            }
            if (leftLng == "未设置")
            {
                XtraMessageBox.Show("请在地图中按Shift键，拖动反键选取区域");
                textEdit_leftlon.Focus();
                return false;
            }
            if (rightLat == "未设置")
            {
                XtraMessageBox.Show("请在地图中按Shift键，拖动反键选取区域");
                textEdit_rightlat.Focus();
                return false;
            }
            if (rightLng == "未设置")
            {
                XtraMessageBox.Show("请在地图中按Shift键，拖动反键选取区域");
                textEdit_rightlon.Focus();
                return false; 
            }
            if(timeEdit_start.Text=="")
            {
                XtraMessageBox.Show("起始时间不能为空");
                timeEdit_start.Focus();
                return false;
            }
            if(timeEdit_end.Text =="")
            {
                XtraMessageBox.Show("结束时间不能为空");
                timeEdit_end.Focus();
                return false;
            }
            if(timeEdit_end.Time<=timeEdit_start.Time)
            {
                XtraMessageBox.Show("结束时间必须大于起始时间");
                timeEdit_end.Focus();
                return false;
            }

            return true;
            
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            if (gridView1.RowCount < 1)
                return;
            if (XtraMessageBox.Show("确认删除该列表内出租车的矩形区域吗？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                int count = 0;
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    int intId = int.Parse(gridView1.GetDataRow(i)["id"].ToString());
                    if (MainForm.PositionService.TaxiAreaExit(intId))
                    {
                        MainForm.PositionService.TaxiAreaDelete(intId);
                        count++;
                    }

                }
                XtraMessageBox.Show("共选择【" + gridView1.RowCount + "辆】出租车，删除成功【" + count
                                    + "辆】，未删除成功的车辆其区域未设置");
            }
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if(row == null) return;
            int id =int.Parse(row["id"].ToString());
            if (!MainForm.PositionService.TaxiAreaExit(id))
            {
                mainMap.SelectedArea = RectLatLng.Empty;
                return;
            }
            DataSet ds = MainForm.PositionService.TaxiAreaGetList(" Taxiid ="+id);
           // LeftLat,LeftLon,RightLat,RightLon,
            double leftLat =Double.Parse(ds.Tables[0].Rows[0]["LeftLat"].ToString());
            double leftLon =Double.Parse(ds.Tables[0].Rows[0]["LeftLon"].ToString());
            double rightLat = Double.Parse(ds.Tables[0].Rows[0]["RightLat"].ToString());
            double rightLon = Double.Parse(ds.Tables[0].Rows[0]["RightLon"].ToString());
            RectLatLng area = new RectLatLng();
            area.LocationTopLeft = new PointLatLng(leftLat,leftLon);
            area.Size = new SizeLatLng(leftLat-rightLat,rightLon-leftLon);
            mainMap.SelectedArea = area;
            mainMap.Position = area.LocationMiddle;
            mainMap.Zoom = mainMap.MinZoom+2; 
        }
        private void MainMapSetCurrentPositionByKeywords(string positionName)
        {
            GeoCoderStatusCode status = mainMap.SetPositionByKeywords(positionName);
            if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
            {
                MessageBox.Show("Google Maps Geocoder can't find: '" + 
               textEdit_address.Text + "', reason: " 
               + status.ToString(), "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void btn_goto_Click(object sender, EventArgs e)
        {
            MainMapSetCurrentPositionByKeywords(textEdit_address.Text.Trim());
        }
    }
}